package com.hmdp.service.impl;


import cn.hutool.cache.Cache;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_NULL_TTL;
import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;

    @Override
    public Result querryById(Long i) {
        //解决缓存穿透
        //Shop shop = querryWithPassThrough(i);
        //使用封装的工具类进行操作，可以实现对不同类型的实体操作
        //cacheClient.querryWithPassThrough();

        //互斥锁解决缓存击穿
        Shop shop = querryWithMutex(i);
        if(shop==null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    public Shop querryWithMutex(Long i) {
        //1：首先去redis中查
        String s = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + i);
        //2: 存在，返回
        if (StrUtil.isNotBlank(s)) {
            Shop shop = JSONUtil.toBean(s, Shop.class);
            return shop;
        }

        //判断命中的是不是空值，命中空值
        if (s != null) {
            return null;
        }
        //3 ：实现缓存重建
        //3.1获取互斥锁
        String lock = RedisConstants.LOCK_SHOP_KEY + i;
        try {
            Boolean aBoolean = tryLock(lock);
            //3.2判断是否获取成功
            if (!aBoolean) {
                //3.3失败，休眠并且重试
                Thread.sleep(200);
                return querryWithMutex(i);
            }
            //3.4 成功，去数据库查
            //先去redis缓存中查取看看这会有没有
            if (StrUtil.isNotBlank(s)) {
                Shop shop = JSONUtil.toBean(s, Shop.class);
                return shop;
            }
            //redis中没有，去数据库中查
            Shop shop = getById(i);
            // 5不存在，返回404 并将数据写入到redis中避免缓存击穿
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + i, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //6 存在，存到redis中 同时设置过期时间
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + i, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            // 8 返回到前端页面
            return shop;
        } catch (InterruptedException e)
        {
            throw new RuntimeException(e);
        }finally{
            //7 释放互斥锁
            unLock(lock);
        }

    }

    //解决缓存穿透的问题
    public Shop querryWithPassThrough(Long i){
        //1：首先去redis中查
        String s = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + i);
        //2: 存在，返回
        if(StrUtil.isNotBlank(s)){
            Shop shop = JSONUtil.toBean(s, Shop.class);
            return shop;
        }

        //判断命中的是不是空值，命中空值
        if(s!=null){
            return null;
        }
        //3 不存在，去数据库查
        Shop shop = getById(i);
        // 4不存在，返回404 并将数据写入到redis中避免缓存击穿
        if(shop==null)
        {
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + i,"", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //5 存在，存到redis中 同时设置过期时间
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + i,JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 7 返回到前端页面

        return shop;
    }

    public Boolean tryLock(String key){
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    public void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        //更新数据库，
        updateById(shop);
        //删除缓存
        Long id = shop.getId();
        if(id==null)
        {
            return Result.fail("店铺不存在");
        }
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 根据类型分页查询
        if(x==null||y==null){
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
                        // 返回数据
                    return Result.ok(page.getRecords());
        }
        //2 计算分页参数
        int from =(current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end=current*SystemConstants.DEFAULT_PAGE_SIZE;

        //3 查询redis,根据当前用户所在的距离,把当前用户当成中心点
        String key=RedisConstants.SHOP_GEO_KEY+typeId;
        final GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().
                //GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                        search(key,
                        GeoReference.fromCoordinate(x, y),//使用redis来处理x,y的坐标
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );

        /*// 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，按数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询redis、按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo() // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );*/
        // 4.解析出id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);


    }
}
